package com.wanxi.spring.cloud.user.service.impl;

import com.wanxi.spring.cloud.commons.api.CommonResult;
import com.wanxi.spring.cloud.user.mapper.RoleMapper;
import com.wanxi.spring.cloud.user.mapper.UserMapper;
import com.wanxi.spring.cloud.user.mapper.UserRoleMapper;
import com.wanxi.spring.cloud.user.model.Code;
import com.wanxi.spring.cloud.user.model.Role;
import com.wanxi.spring.cloud.user.model.User;
import com.wanxi.spring.cloud.user.model.UserRole;
import com.wanxi.spring.cloud.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 蒋帆
 * @since 2020-12-21
 */
@Service
@CacheConfig(cacheNames = "springcloud::user")
public class UserServiceImpl implements UserService {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    RedisServiceImpl redisService;
    @Autowired(required = false)
    UserMapper userMapper;
    @Autowired(required = false)
    UserRoleMapper userRoleMapper;
    @Autowired(required = false)
    RoleMapper roleMapper;

    @Override
    public CommonResult getUserByName(String username) {//根据用户名获取用户
        User user = null;//判断缓存是否有该用户
        if (!redisService.hasKey("springcloud::user::" + username))
            user = userMapper.getUserByName(username);//如果没有，访问数据库
        else//如果有，则直接从缓存中拿到该值
            user = (User) redisService.get("springcloud::user::" + username);
        return CommonResult.success(user);
    }

    @Override//用户注册
    public CommonResult register(User user) {
        //将密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //设置用户的初始值
        user.setEnable("yes");
        user.setStatus("normal");
        //添加用户
        int result = userMapper.register(user);
        if (result > 0) {//如果添加成功
            if (user.getRole() != null) {//判断用户是否选择了角色
                //如果选择了角色，则将用户角色添加到用户角色表中
                UserRole userRole = new UserRole();
                userRole.setRole(user.getRole()).setUser(user.getId());
                userRoleMapper.addUserRole(userRole);
            }
            //生成该用户信息缓存到Redis
//            redisService.set("springcloud::user::" + user.getCode(), user);
            //删除用户信息列表
            redisService.del("springcloud::user::getUsers");
            return CommonResult.success(user, "注册成功！");
        }
        return CommonResult.failed("注册失败");
    }

    /**
     * 获取用户列表
     *
     * @param map
     * @return
     */
    @Override
    public CommonResult getUsers(Map map) {
        int page = (Integer.parseInt((String) map.get("page")) - 1) * Integer.parseInt((String) map.get("limit"));
        map.put("page", page);
        map.put("limit", Integer.parseInt((String) map.get("limit")));
        List<User> users = userMapper.getUsers(map).stream().map(u -> {
            //封装用户状态（是否冻结）
            if (redisService.hasKey("springcloud::user::" + u.getCode() + "::frozen"))
                u.setStatus("<input type='checkbox' value='" + u.getCode() + "' name='status' lay-filter='status' lay-skin='switch' lay-text='正常|冻结'>");
            else
                u.setStatus("<input type='checkbox' value='" + u.getCode() + "' name='status' lay-filter='status' lay-skin='switch' lay-text='正常|冻结' checked>");
            //封装用户头像
            File file = new File("E:/IdeaWorksplace/team_manage_system/src/main/resources/static" + u.getIcon());
            if (!file.exists()) {
                if (u.getIcon() != null && u.getIcon() != "") {
                    //判断是否是base64
                    int index = u.getIcon().indexOf(",");
                    if (index == -1)
                        u.setIcon("http://t.cn/RCzsdCq");
                    else {
                        String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
                        boolean match = Pattern.matches(base64Pattern, u.getIcon().substring(index + 1));
                        if (!match)
                            u.setIcon("http://t.cn/RCzsdCq");
                    }
                } else
                    u.setIcon("http://t.cn/RCzsdCq");
            }
            //封装用户角色
            Role role = roleMapper.getRoleByUserId(u.getId());
            if (role != null) {
                u.setRole(role.getId());
                u.setRoleName(role.getName());
            }
            return u;
        }).collect(Collectors.toList());
        long count = userMapper.getUserCount(map);
        return CommonResult.success(users, count);
    }

    /**
     * 删除用户
     *
     * @param code
     * @return
     */
    @Override
    public CommonResult deleteUser(String code) {
        int result = userMapper.deleteUser(code);
        if (result > 0) {
            redisService.del("springcloud::user::" + code);
            return CommonResult.success(result, "删除成功");
        }
        return CommonResult.failed("删除失败");
    }

    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @Override
    public CommonResult updateUser(User user) {
        if (user.getPassword() != "") {//如果密码不为空，
            user.setPassword(passwordEncoder.encode(user.getPassword()));//将密码加密
        }//修改用户信息
        int result = userMapper.updateUser(user);
        if (result > 0) {//如果修改成功
            if (user.getRole() != null) {//如果选择了用户角色
                UserRole userRole = userRoleMapper.getUserRoleByUser(user.getId());//查找数据库用户角色表是否有该用户角色信息
                if (userRole == null) {//如果没有，则添加
                    userRole = new UserRole();
                    userRole.setRole(user.getRole()).setUser(user.getId());
                    userRoleMapper.addUserRole(userRole);
                } else
                    userRoleMapper.updateUserRole(userRole);
            }//修改成功后删除Redis缓存中的用户列表和该修改后用户的数据，以便下次刷新
            redisService.del("springcloud::user::getUsers", "springcloud::user::" + user.getCode());
//            redisService.set("springcloud::user::" + user.getCode(), user,86400);
            return CommonResult.success(user, "修改成功！");
        }
        return CommonResult.failed("修改失败");
    }

    /**
     * 获取码表信息
     *
     * @return
     */
    @Override
    public CommonResult getCodeList() {
        HashMap data = new HashMap();
        List<Code> codeList = null;
        codeList = userMapper.getCodeList();
        List<Code> sex = new ArrayList<>();
        List<Code> graduate = new ArrayList<>();
        List<Code> enable = new ArrayList<>();
        List<Code> userStatus = new ArrayList<>();
        List<Code> permissionType = new ArrayList<>();
        List<Code> signStatus = new ArrayList<>();
        List<Code> dailySummaryEditStatus = new ArrayList<>();
        List<Code> dailySummaryReadStatus = new ArrayList<>();
        //将码表分类存放
        for (Code code : codeList) {
            if (code.getType().equals("sex"))
                sex.add(code);
            else if (code.getType().equals("graduate"))
                graduate.add(code);
            else if (code.getType().equals("enable"))
                enable.add(code);
            else if (code.getType().equals("user_status"))
                userStatus.add(code);
            else if (code.getType().equals("permission_type"))
                permissionType.add(code);
            else if (code.getType().equals("sign_status"))
                signStatus.add(code);
            else if (code.getType().equals("daily_summary_edit_status"))
                dailySummaryEditStatus.add(code);
            else if (code.getType().equals("daily_summary_read_status"))
                dailySummaryReadStatus.add(code);
        }
        data.put("sex", sex);
        data.put("graduate", graduate);
        data.put("enable", enable);
        data.put("user_status", userStatus);
        data.put("permission_type", permissionType);
        data.put("sign_status", signStatus);
        data.put("daily_summary_edit_status", dailySummaryEditStatus);
        data.put("daily_summary_read_status", dailySummaryReadStatus);
        return CommonResult.success(data);
    }

    /**
     * 更新用户状态（冻结/解冻）
     *
     * @param code
     * @param status
     * @return
     */
    @Override
    public CommonResult updateStatus(String code, String status) {
        if (status.equals("frozen")) {
            redisService.set("springcloud::user::" + code + "::frozen", true);
            return CommonResult.success("frozen");
        } else {
            redisService.del("springcloud::user::" + code + "::frozen");
            return CommonResult.success("normal");
        }
    }

    /**
     * 获取组长信息
     *
     * @return
     */
    @Override
    public CommonResult getLeaderList() {
        List<User> users = userMapper.getLeaderList();
        return CommonResult.success(users);
    }

    /**
     * 获取教练信息
     *
     * @return
     */
    @Override
    public CommonResult getCoachList() {
        List<User> users = userMapper.getCoachList();
        return CommonResult.success(users);
    }

    /**
     * 获取小组用户
     *
     * @param teamId
     * @return
     */
    @Override
    public CommonResult getTeamUser(Integer teamId) {
        List<User> users = userMapper.getTeamUser(teamId);
        List<User> teamMember = userMapper.getInTeamMembers(teamId);
        List<Integer> collect = teamMember.stream().map(m -> m.getId()).collect(Collectors.toList());
        HashMap data = new HashMap();
        data.put("members", users);
        data.put("inTeamMember", teamMember);
        data.put("inTeamMemberIds", collect);
        return CommonResult.success(data);
    }

    /**
     * 获取小组成员
     *
     * @param teamId
     * @return
     */
    @Override
    public CommonResult getTeamMember(Integer teamId) {
        List<User> teamMember = userMapper.getTeamMember(teamId);
        return CommonResult.success(teamMember);
    }

    /**
     * 通过该用户id获取该小组成员信息
     *
     * @param userId
     * @return
     */
    @Override
    public CommonResult getTeamMemberByUser(Integer userId) {
        List<User> users = userMapper.getTeamMemberByUser(userId);
        return CommonResult.success(users);
    }

    /**
     * 获取该用户小组中未签到的成员信息
     *
     * @param userId
     * @return
     */
    @Override
    public CommonResult getNoSignTeamMemberByUser(Integer userId) {
        List<User> users = userMapper.getNoSignTeamMemberByUser(userId);
        return CommonResult.success(users);
    }

    @Override
    public User selectUserById(int id) {
        return userMapper.selectUserById(id);
    }

    @Override
    public User getUserByCode(String code) {
        return userMapper.getUserByName(code);
    }

    @Override
    public int updateUserRole(UserRole userRole) {
        return userRoleMapper.updateUserRole(userRole);
    }

}
